package com.it.boot.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.it.boot.config.ApiResult;
import com.it.boot.entity.DeptEntity;
import com.it.boot.entity.UserEntity;
import com.it.boot.mapper.UserBatisMapper;
import com.it.boot.util.BoolUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserService extends ServiceImpl<UserBatisMapper, UserEntity> {

    @Resource
    private UserBatisMapper userBatisMapper;

    public IPage<UserEntity> batisPage(Page<UserEntity> page, UserEntity entity) {
        return userBatisMapper.getPage(page, entity);
    }

    public IPage<UserEntity> getPage(Page<UserEntity> page, UserEntity entity) {
        page.setSize(page.getSize());
        LambdaQueryWrapper<UserEntity> wrapper = buildQueryWrapper(entity);
        wrapper.orderByDesc(UserEntity::getCreateTime);
        return this.page(page, wrapper);
    }

    private LambdaQueryWrapper<UserEntity> buildQueryWrapper(UserEntity param) {
        LambdaQueryWrapper<UserEntity> lqw = Wrappers.lambdaQuery();
        lqw.like(BoolUtils.toBool(param.getUserName()), UserEntity::getUserName, param.getUserName());
        return lqw;
    }
    public ApiResult<IPage<UserEntity>> join(Page<UserEntity> page, List<Integer> ids) {
        MPJLambdaWrapper<UserEntity> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(UserEntity.class);
        wrapper.leftJoin(DeptEntity.class, DeptEntity::getId, UserEntity::getDeptId);
        wrapper.selectAs(DeptEntity::getName, UserEntity::getDeptName);
        wrapper.in(UserEntity::getId, ids);
        return ApiResult.success(userBatisMapper.selectJoinPage(page, UserEntity.class, wrapper));
    }

    public UserEntity getUserById(Integer id) {
        return this.getBaseMapper().getUserById(id);
    }
}